package com.cm.projectx.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;

/**
 * excel工具类
 */
@Slf4j
public class ExcelUtils {

    private ExcelUtils() {}

    /**
     * 简化版Excel导出 - 使用更可靠的文件名编码方法
     */
    public static void exportExcel(HttpServletResponse response, String fileName,
                                   Collection<?> list, Class<?> pojoClass,
                                   ExportParams exportParams) throws IOException {

        // 确保文件名有正确的扩展名
        if (!fileName.toLowerCase().endsWith(".xlsx")) {
            fileName += ".xlsx";
        }

        // 使用简单的URL编码方法
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName);

        // 使用EasyPOI导出Excel
        Workbook workbook = null;
        try {
            workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);

            // 写入响应流
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
                out.flush();
            }
        } finally {
            // 确保关闭工作簿
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    // 记录日志但不要抛出异常
                    System.err.println("关闭工作簿时出错: " + e.getMessage());
                }
            }
        }
    }
}